// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "azure_c_shared_utility/platform.h"
#include "azure_c_shared_utility/optimize_size.h"
#include "azure_c_shared_utility/xio.h"
#include "azure_c_shared_utility/tlsio_mbedtls.h"
#include "azure_c_shared_utility/http_proxy_io.h"
#include "azure_c_shared_utility/socketio.h"
#include "api.h"
#include "net.h"
#include "xos2.h"
#include "NTPClient.h"
#include "mbedtls/platform_time.h"

#ifdef DEVICE_RTC
#include "platform/mbed_rtc_time.h"
#endif

time_t now_time;

extern "C" {
#ifndef DEVICE_RTC
	time_t time(time_t *timer) {
		time_t t;
		t = now_time + (xos::TickGet() / 1000);
		if (timer != NULL) {
			*timer = t;
		}
		return t;
	}
#endif
#if USE_MBED_TLS==1	
	mbedtls_time_t __mbedtls_time(mbedtls_time_t* timer) {
		return time((time_t *)timer);
	}
	int mbedtls_hardware_poll(void *data, unsigned char *output, size_t len, size_t *olen) {
		uint32_t timer;

		if (len < sizeof(uint32_t)) {
			*olen = 0;
			return (0);
		}
		timer = time(NULL);
		memcpy(output, &timer, sizeof(timer));
		*olen = sizeof(timer);
		return (0);
	}
#endif	
}

int setupRealTime(void)
{
    int result = 0;

	NTPClient ntp;
	ntp.set_server("ntp1.aliyun.com", 123);
	time_t now = ntp.get_timestamp(1000);
	if (now <= 0) {
		ntp.set_server("ntp2.aliyun.com", 123);
		now = ntp.get_timestamp(1000);
		if (now <= 0) {
			ntp.set_server("ntp3.aliyun.com", 123);
			now = ntp.get_timestamp(1000);
		}
	}
	if (now) {
#ifdef DEVICE_RTC
		set_time(now);
#endif
		now_time = now - (xos::TickGet() / 1000);
		srand(now_time);
#if USE_MBED_TLS==1
		mbedtls_platform_set_time(__mbedtls_time);
#endif		
	}
	else {
		result = __FAILURE__;
	}
    return result;
}

int platform_init(void)
{
    int result;
    result = 0;
    return result;
}

const IO_INTERFACE_DESCRIPTION* platform_get_default_tlsio(void)
{
#if USE_MBED_TLS==1
    return tlsio_mbedtls_get_interface_description();
#else
    return socketio_get_interface_description();
#endif		
}

STRING_HANDLE platform_get_platform_info(void)
{
    // Expected format: "(<runtime name>; <operating system name>; <platform>)"

    return STRING_construct("(native; mbed; undefined)");
}

void platform_deinit(void)
{
}
